<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "ScrollList",
});
</script>
<script setup lang="ts">
import { withDefaults, onMounted, ref } from "vue";
import { usePageScroll } from "@/hooks/scroll";
import { useList } from "@/hooks/page";
import ListMore from "@/components/list/more.vue";
import { onLoad, onPageScroll, onReachBottom } from "@dcloudio/uni-app";
import ListEmpty from "@/components/list/empty.vue";
const porps = withDefaults(
  defineProps<{
    api: Function;
    query: any;
    page: number;
    pageSize: number;
    height: string;
    empty: string;
  }>(),
  {
    api: () => {},
    query: {},
    page: 1,
    pageSize: 10,
    height: "fit-content",
    empty: "咦~什么内容都没有…",
  }
);
const emit = defineEmits(["getList", "loadMoreList", "pagination"]);
const firstLoad = ref(false);
const pagination = ref(0);
onMounted(() => {
  reloadList().then(() => {
    emit("getList", listData.value);
    emit("pagination", pagination.value);
    setTimeout(() => {
      listLoadMore.value = listData.value.length > 1;
    });
  });
});
onPageScroll(() => {
  listLoadMore.value = listData.value.length > 1;
});
onReachBottom(() => {
  loadMoreList().then(() => {
    emit("loadMoreList", listData.value);
  });
});
const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: porps.page, page_size: porps.pageSize }, (query) => {
    return porps
      .api({
        ...query,
        ...porps.query,
      })
      .then((res: any) => {
        pagination.value = res.pagination;
        firstLoad.value = true;
        return res;
      });
  });
const getList = () => {
  return reloadList().then((res) => {
    listLoadMore.value = listData.value.length > 1;
    emit("getList", listData.value);
  });
};
const reload = () => {
  return reloadList().then((res) => {
    listLoadMore.value = listData.value.length > 1;
    emit("getList", listData.value);
  });
};
defineExpose({
  listData,
  listStatus,
  listLoadMore,
  getList,
  loadMoreList,
  reload,
});
</script>

<template>
  <view class="ScrollListWrap" v-if="listData.length">
    <slot :list="listData" :reloadList="reloadList" />
    <ListMore
      v-if="listLoadMore"
      :status="listStatus"
      :safeAreaInsetBottom="false"
    />
  </view>
  <view class="empty" v-else >
      <ListEmpty :text="empty" />
  </view>

</template>

<style lang="scss">
.ScrollListWrap {
  width: 100%;
  height: 100%;
}
.empty {
  margin-top: 300rpx;
}
</style>
